#!/bin/bash

export LANG=en_US.UTF-8
ADDR_FILE="$(dirname $0)/conn.list"
LOG_PATH="/var/log/monitor"
LOG_NAME="conn"
INTERVAL=60

function Init {
    local self_count=$(pgrep -cx "$(basename $0)")
    [ 0 -eq $? ] || exit 1
    [ 1 -eq $self_count ] || exit 1
    mkdir -p $LOG_PATH || exit 1
}

function Log {
    local msg="$1"
    local log_time="$(date +'%F %T')"
    local log_file="$LOG_PATH/$LOG_NAME-${log_time% *}.log"
    echo "$log_time $msg" >> $log_file
    cd $LOG_PATH && ls ${LOG_NAME}-* 2>/dev/null \
        | head -n -7 | xargs rm -f
}

function CountAddrConn {
    local addr=$1
    local server="${addr%:*}"
    local port="${addr#*:}"
    local count=0
    if [ 'localhost' = "$server" ]; then
        count=$(ss -anpt | awk '{print $4}' \
            | grep -c ":$port$")
    else
        count=$(ss -anpt | awk '{print $5}' \
            | grep -c "$addr$")
    fi
    echo "$server $port $count"
}

function Main {
    local addr=
    sleep $INTERVAL
    for addr in $(cat $ADDR_FILE); do
        Log "$(CountAddrConn $addr)"
    done
}

# start
Init
Main

